#include "Ray.h"
#include "Triangle.h"

Ray::Ray(const Vector3D& position, const Vector3D& direction)
:	position(position), direction(direction) {
}

bool Ray::intersects(const Triangle& triangle, float& distance) const {
	Vector3D pvec, tvec, qvec;
	
	Vector3D edge1 = triangle.vector2 - triangle.vector1;
	Vector3D edge2 = triangle.vector3 - triangle.vector1;

	pvec = direction.crossProduct(edge2);
	
	float det = edge1 * pvec;
	
	if (det < 0.0001f && det > -0.0001f) {
		return false;
	}
	
	tvec = position - triangle.vector1;
	float u = tvec * pvec;
	if (u < 0.0f || u > det) {
		return false;
	}
	
	qvec = tvec.crossProduct(edge1);
	float v = direction * qvec;
	if (v < 0.0f || u + v > det) {
		return false;
	}
	
	distance = edge2 * qvec;
	float fIntDev = 1.0f / det;
	distance *= fIntDev;
	
	return true;
}


